﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using Al_FrameWork;
using NUnit.Framework;
using UnityEditor;
using UnityEditor.Experimental.Rendering;
using UnityEngine;

namespace Editor
{
    public class ABIOTools
    {
        /// <summary>
        /// 判断当前打包环境
        /// </summary>
        /// <param name="buildTarget"></param>
        /// <returns></returns>
        public static string GetPlatformName(BuildTarget buildTarget)
        {
            switch (buildTarget)
            {
                case BuildTarget.Android:
                    return "Android";
                case BuildTarget.StandaloneWindows:
                    return "Windows";
                case BuildTarget.StandaloneWindows64:
                    return "Windows";
                case BuildTarget.iOS:
                    return "IOS";
                default:
                    return "unKnown";
            }
        }
        
        /// <summary>
        /// 文件大小
        /// </summary>
        /// <param name="size"></param>
        /// <returns></returns>
        public static string FileSizeFormat(int size)
        {
            if (size < 1024)
            {
                return size + "KB";
            }
            else
            {
                return string.Format("{0:N2}MB", size / 1024);
            }
        }

        /// <summary>
        /// 转成Unity路径
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string FormatToUnityPath(string path)
        {
            return path.Replace("\\", "/");
        }

        /// <summary>
        /// CheckOrCreateDir
        /// </summary>
        /// <param name="path"></param>
        public static void CheckOrCreateDir(string path)
        {
            if (string.IsNullOrEmpty(path) || string.IsNullOrWhiteSpace(path))
                return;

            //清空文件夹
            if (Directory.Exists(path))
            {
                GlobalFunctions.LOG("清空文件夹[{0}]", path);
                DeleteDirectories(path);
            }

            Directory.CreateDirectory(path);
        }

        /// <summary>
        ///  获取当前assetBundles 输出目录
        /// </summary>
        /// <param name="buildTarget">构建assetbundle的平台</param>
        /// <returns>当前平台的assetbundles的输出目录</returns>
        public static string GetAssetBundleOutputPath(BuildTarget buildTarget)
        {
            var outputPath = Path.Combine(AssetBundlesBuildOutputPath(GameConfig.AssetBundlesFolderName),
                GetPlatformName(buildTarget));
            return outputPath;
        }
        
        /// <summary>
        /// AssetBundlesBuildOutputPath
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string AssetBundlesBuildOutputPath(string path)
        {
            var outputPath = Path.Combine(Environment.CurrentDirectory, path);
            return outputPath;
        }

        /// <summary>
        /// 创建目录
        /// </summary>
        /// <param name="folderPath"></param>
        public static void CheckDirAndCreateWhenNeeded(string folderPath)
        {
            if (string.IsNullOrEmpty(folderPath))
            {
                return;
            }

            if (Directory.Exists(folderPath))
            {
                DeleteDirectories(folderPath);
            }

            Directory.CreateDirectory(folderPath);
        }

        /// <summary>
        /// 删除目录
        /// </summary>
        public static void DeleteDirectories(string dirPath)
        {
            if (string.IsNullOrEmpty(dirPath) || string.IsNullOrWhiteSpace(dirPath))
            {
                return;
            }

            string[] files = Directory.GetFiles(dirPath);
            string[] dirs = Directory.GetDirectories(dirPath);

            foreach (string file in files)
            {
                File.SetAttributes(file, FileAttributes.Normal);
                File.Delete(file);
            }

            foreach (string dir in dirs)
            {
                DeleteDirectories(dir);
            }

            Directory.Delete(dirPath, false);
        }

        /// <summary>
        /// 获取路径下所有文件夹子
        /// </summary>
        /// <param name="dirPath"></param>
        public static void GetAllDirectorysInPath(string dirPath, in List<string> directories)
        {
            if (string.IsNullOrWhiteSpace(dirPath) || string.IsNullOrEmpty(dirPath))
            {
                return;
            }

            if (!Directory.Exists(dirPath))
            {
                return;
            }

            string[] dirs = Directory.GetDirectories(dirPath);
            foreach (string dir in dirs)
            {
                directories.Add(dir);
                GetAllDirectorysInPath(dir, in directories);
            }
        }

        /// <summary>
        /// 获取路径下所有文件
        /// </summary>
        /// <param name="dirPath"></param>
        /// <param name="files"></param>
        public static void GetFilesInPath(string dirPath, in List<string> files,
            string ignoresuffix = ABPackConfig.filtermetasuffix)
        {
            List<string> ignoresuffixList = new List<string>();
            ignoresuffixList.Add(ABPackConfig.filtermetasuffix);
            ignoresuffixList.Add(ABPackConfig.filtermanifestsuffix);
            if (string.IsNullOrWhiteSpace(dirPath) || string.IsNullOrEmpty(dirPath))
            {
                return;
            }

            if (!Directory.Exists(dirPath))
            {
                return;
            }

            string[] dirs = Directory.GetDirectories(dirPath);
            foreach (string dir in dirs)
            {
                GetFilesInPath(dir, files);
            }

            string[] files_ = Directory.GetFiles(dirPath, "*.*", SearchOption.AllDirectories);
            var CurrentDirfiles = files_.Where(file__ => !ignoresuffixList.Any(ignore => file__.EndsWith(ignore)));
            foreach (string file in CurrentDirfiles)
            {
                files.Add(file);
            }
        }


        /// <summary>
        /// 复制文件夹
        /// </summary>
        /// <param name="sourcePath"></param>
        /// <param name="DestinationPath"></param>
        public static void CopyDirectories(string sourcePath, string destinationPath)
        {
            if (string.IsNullOrEmpty(sourcePath) || string.IsNullOrWhiteSpace(sourcePath))
            {
                GlobalFunctions.Err("sourcePath is null or empty");
                return;
            }

            if (string.IsNullOrEmpty(destinationPath) || String.IsNullOrWhiteSpace(destinationPath))
            {
                GlobalFunctions.Err("destinationPath is null or empty");
                return;
            }

            if (!Directory.Exists(sourcePath))
            {
                GlobalFunctions.Err("directory {0} is not exist,please check", sourcePath);
                return;
            }

            if (!Directory.Exists(destinationPath))
            {
                Directory.CreateDirectory(destinationPath);
            }
            
        }
        
        /// <summary>
        /// 获取文件夹下所有文件信息
        /// </summary>
        /// <param name="dirPath"></param>
        /// <returns></returns>
        public static List<FileInfo> GetFileInfos(string dirPath)
        {
            int length = 0;
            List<FileInfo> fileInfoList = new List<FileInfo>();
            DirectoryInfo directory = new DirectoryInfo(dirPath);
            FileInfo[] fileInfos = directory.GetFiles("*",SearchOption.AllDirectories);
            length = fileInfos.Length;
            for (int i = 0; i < length; i++)
            {
                fileInfoList.Add(fileInfos[i]);
            }

            //获取文件夹下所有文件夹
            string[] folders = Directory.GetDirectories(dirPath);
            length = folders.Length;
            for (int i = 0; i < length; i++)
            {
                List<FileInfo> lst = GetFileInfos(folders[i]);
                int len = lst.Count;
                for (int j = 0; j < len; j++)
                {
                    fileInfoList.Add(lst[j]);
                }
            }

            return fileInfoList;
        }


        /// <summary>
        /// 生成文件的MD5码
        /// </summary>
        /// <returns></returns>
        public static string GetFileMD5Code(string file)
        {
            string md5Code = "";
            if (string.IsNullOrEmpty(file) || string.IsNullOrWhiteSpace(file))
            {
                Debug.LogError("file is null or Empty");
                return md5Code;
            }

            if (!File.Exists(file))
            {
                Debug.LogError("file is not exist!");
                return md5Code;
            }


            try
            {
                FileStream fs = new FileStream(file, FileMode.Open);
                MD5 md5 = new MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(fs);
                fs.Close();
                fs.Dispose();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    //将数据转化成小写的16进制
                    sb.Append(retVal[i].ToString("x2"));
                }

                md5Code = sb.ToString();
            }
            catch (Exception e)
            {
                throw new Exception("md5file() fail,error:" + e.Message);
            }

            return md5Code;
        }
    }
}